package com.sykj.why.mongo.service.impl;

import com.sykj.why.exception.WhyException;
import com.sykj.why.mongo.document.entity.AlbumT;
import com.sykj.why.mongo.document.entity.SolrDocumentT;
import com.sykj.why.mongo.dto.PageDTO;
import com.sykj.why.mongo.enums.exception.ResultEnum;
import com.sykj.why.mongo.service.AlbumTService;
import com.sykj.why.mongo.service.SolrService;
import com.sykj.why.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Eleven
 * @date 2019/6/18
 * @desc Solr业务实现层
 */

@Service
@Slf4j
public class SolrServiceImpl implements SolrService {

    @Autowired
    SolrClient client;
    @Value("${spring.data.solr.solrCore}")
    private String solrCore;
    @Autowired
    private AlbumTService albumTService;

    /**
     * 添加资源方法
     *
     * @param solr
     */
    @Override
    public void add(SolrDocumentT solr) throws IOException, SolrServerException {
        client.addBean(solrCore, solr);
        client.commit(solrCore);
    }

    /**
     * 添加多个资源方法
     *
     * @param list
     */
    @Override
    public void add(List<SolrDocumentT> list) {
        try {
            client.addBeans(solrCore, list);
            client.commit(solrCore);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("添加资源到Solr中出错了{}");
        }
    }

    @Override
    public void update(SolrDocumentT solrDocumentT) {

    }

    /**
     * 根据id删除
     *
     * @param id
     */
    @Override
    public void remove(String id) {
        try {
            client.deleteById(solrCore, id);
            client.commit(solrCore);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("根据删除资源到Solr中出错了{}");
        }
    }

    @Override
    public void removeAll() {
        try {
            client.deleteByQuery(solrCore, "*:*");
            client.commit(solrCore);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除资源到Solr中出错了{}");
        }
    }

    @Override
    public List<SolrDocumentT> findAll() {
        return null;
    }

    /**
     * 根据检索词查询 Solr资源数据
     *
     * @param pageDTO 分页查询入参对象
     * @return
     * @throws IOException
     * @throws SolrServerException
     */
    @Override
    public Page findByPage(PageDTO pageDTO) throws IOException, SolrServerException {
        //入参判断为空报错
        if (StringUtil.isBlank(pageDTO.getParamName())) {
            throw new WhyException(ResultEnum.NAMEISNULL);
        }
        SolrQuery query = new SolrQuery();
        // 设置查询的关键词
        query.set("q","title_txt:" + pageDTO.getParamName());
        query.set("fq","type:" + pageDTO.getType());
        query.set("fq","enable:true");
        if (!StringUtil.isBlank(pageDTO.getCategoryId())) {
            query.set("fq","source_category:"+pageDTO.getCategoryId());
        }
        //分页
        query.setRows(pageDTO.getLineSize());
        query.setStart((pageDTO.getCurrentPage() - 1) * pageDTO.getLineSize());
        //query.addFilterQuery("summary:" + pageDTO.getParamName(),"title_txt:"+pageDTO.getParamName());
        // 设置高亮显示
        query.setHighlight(true);
        // 高亮显示的字段
        query.addHighlightField("title_txt,summary");
        // 高亮的样式
        query.setHighlightSimplePre("<span style='color:red'>");
        query.setHighlightSimplePost("</span>");

        // 执行查询
        QueryResponse response = client.query(solrCore, query);
        SolrDocumentList results = response.getResults();
        long count = results.getNumFound();
        //获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的
        Map<String, Map<String, List<String>>> highlight = response.getHighlighting();

        List<SolrDocumentT> list = new ArrayList<>();

        if (StringUtils.isNotBlank(pageDTO.getFromId())) {
            List<AlbumT> allAlbum = albumTService.findByProgramaId(pageDTO.getFromId());
            if (allAlbum.size()>0){
                for (AlbumT albumT:allAlbum){
                    for (SolrDocument result : results) {
                        if (albumT.getId().equals(result.get("id"))){
                            SolrDocumentT solr = new SolrDocumentT();
                            // 设置高亮显示字段
                            Map<String, List<String>> ligthList = highlight.get(result.get("id"));
                            List<String> title = ligthList.get("title_txt");
                            List<String> summary = ligthList.get("summary");
                            List<Integer> type = (List<Integer>) result.get("type");
                            List<String> typeName = (List<String>) result.get("typeName");
                            List<String> cover = (List<String>) result.get("cover");
                            List<String> sourceUrl = (List<String>) result.get("source_url");
                            List<String> sourceCategory = (List<String>) result.get("source_category");
                            List<String> categoryName = (List<String>) result.get("categoryName");
                            solr.setId(result.get("id"));
                            solr.setType(type.get(0));
                            solr.setTypeName(typeName.get(0));
                            solr.setTitle(title.get(0));
                            if (summary!=null){
                                solr.setSummary(summary.get(0));
                            }else {
                                solr.setSummary("");
                            }
                            if (cover!=null){
                                solr.setCover(cover.get(0));
                            }else {
                                solr.setCover("");
                            }
                            solr.setSource_url(sourceUrl.get(0));
                            solr.setSource_category(sourceCategory.get(0));
                            if (categoryName!=null){
                                solr.setCategoryName(categoryName.get(0));
                            }else {
                                solr.setCategoryName("");
                            }
                            list.add(solr);
                        }
                    }
                }
            }
        }
        return new Page(pageDTO, count, list);
    }

}
